大家好,我是Leo
今天要來講解是如何透過celery使用redius進行排程
OK~~~ Let's go now!!!
LANGUAGE_CODE = "en-us"
TIME_ZONE = "Asia/Taipei"
USE_I18N = True
USE_L10N = True
USE_TZ = False
django-celery-beat==2.5.0
django-celery-results==2.5.1
celery==5.2.7
這邊版本參考,如太舊的版本celery可能會遇到contab設定時間的問題
# test for cache using redis
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
},
}
# Celery settings
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"
#將時區更改為TAIPEI
CELERY_ENABLE_UTC = False
TIME_ZONE = "Asia/Taipei"
#django_celery_beat的clockedschedule任務是默認是用UTC時區的
DJANGO_CELERY_BEAT_TZ_AWARE = False
CELERY_TASK_TIME_LIMIT = 5
# django-cache to tasks result and status
CELERY_RESULT_BACKEND = "django-db"
# celery content format
CELERY_ACCEPT_CONTENT = [
"application/json",
]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_RESULT_EXTENDED = True
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
contab 設定定期任務,圖下test_task2代表tapie時間1700會執行test_task1任務
interval 設定多少秒執行一次,圖下test_task2為一分鐘執行一次的任務
CELERY_BEAT_SCHEDULE = {
contab
"test_task1": {
"task": "website.tasks.test_task",
"schedule": crontab(minute=0, hour=17),
},
intervals
"test_task2": {
"task": "website.tasks.test_task",
"schedule": 60
},
}
執行完會長出celery相關的table
python manage.py migrate
mysite/mysite/celery.py
import os
from celery import Celery
import datetime
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
app = Celery("mysite")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
website/tasks.py
from celery import Celery
from celery import shared_task
import datetime
app = Celery("django_practice")
@shared_task()
def test_task():
return 'finish:' + str(datetime.datetime.now())
預設的 concurrency 值為機器的 CPU 核心數量
可以用 -l 或 --loglevel 參數指定輸出記錄的層級為 INFO 或 DEBUG
Eventlet & Gevent 池使用協程 來執行任務,不是產生傳統線程. 能夠同時處理多個任務
需先開worker再開beat,任務時程較不會有誤差
Celery -A mysite worker --concurrency=4 -l info -P eventlet
關於排程時間
celery -A mysite beat
今天執行celery的排程任務,接下來我們來講解celery的多進程的異步方法
我們明天見,各位掰掰~~~